package com.softserveinc.moviedbapp.parser;

import android.util.Log;

import com.softserveinc.moviedbapp.model.MovieInfo;
import com.softserveinc.moviedbapp.util.MovieAppConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class JSONParserMovieInfo implements IMovieDBMethodGetInfo {

	private static final String TAG = JSONParserMovieInfo.class.getSimpleName();

	@Override
	public MovieInfo parseMovieInfo(final InputStream is) {
		MovieInfo movieInfo = new MovieInfo();

		int retrys = MovieAppConstants.RETRY_COUNT;
		while (retrys > 0) {
			try {
				String jsonString = JSONHelper.convertStreamToString(is);

				JSONArray jsonArray = new JSONArray(jsonString);
				JSONObject movieInfoJson = jsonArray.getJSONObject(0);

				movieInfo.setMovieId(movieInfoJson.getInt("id"));
				movieInfo.setLastModifiedAt(movieInfoJson.getString("last_modified_at"));
				movieInfo.setOverview(movieInfoJson.getString("overview"));
				movieInfo.setTrailerUrl(movieInfoJson.getString("trailer"));

				/* set movie's cast */
				JSONArray castJsonArray = movieInfoJson.getJSONArray("cast");
				JSONObject personJsonObject;
				List<String> cast = new ArrayList<String>();
				for (int i = 0; i < castJsonArray.length(); i++) {
					personJsonObject = castJsonArray.getJSONObject(i);

					if (personJsonObject.getString("job").equals("Actor")) {
						cast.add(personJsonObject.getString("name"));
					}
				}
				movieInfo.setCast(cast);

				/* set movie's image urls */
				movieInfo.setImagesUrls(new HashMap<String, List<String>>());

				JSONArray backdropJsonArray = movieInfoJson.getJSONArray("backdrops");
				for (int i = 0; i < backdropJsonArray.length(); i++) {
					JSONObject imageJsonObject = backdropJsonArray.getJSONObject(i).getJSONObject("image");
					String size = imageJsonObject.getString("size");
					if (size.equals("thumb") || size.equals("poster")) {
						/* add image type and size to ArrayList */
						List<String> typeSizeList = new ArrayList<String>();
						typeSizeList.add(imageJsonObject.getString("type"));
						typeSizeList.add(size);

						/* then get the image url and use it as a map key and type-size list as values */
						movieInfo.getImagesUrls().put(imageJsonObject.getString("url"), typeSizeList);
					}
				}

				Log.d(TAG, "JSON Parsing succeeded, movieInfo\n" + movieInfo.toString());
				break;
			} catch (JSONException e) {
				Log.e(TAG, "JSON Movie info parsing failed.", e);
				retrys--;
				continue;
			}
		}
		try {
			is.close();
		} catch (IOException e) {
			Log.w(TAG, "unable to close input stream", e);
			e.printStackTrace();
		}
		return movieInfo;

	}
}
